package com.gecba.modular.jpa.service;

import com.gecba.modular.jpa.repository.BaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.io.Serializable;
import java.util.List;

/**
 * @author ChenBo
 * @interfaceName IService
 * @date 2021/9/8
 */
public interface IService <E, ID extends Serializable>{

    /**
     * 获取对应 entity 的 BaseMapper
     *
     * @return BaseMapper
     */
    BaseRepository<E,ID> getBaseRepository();

    /**
     * 获取 entity 的 class
     *
     * @return {@link Class<E>}
     */
    Class<E> getEntityClass();

    /**
     *添加
     *@author ChenBo
     *@date 2021/9/9
     */
    @Transactional(propagation = Propagation.SUPPORTS,rollbackFor = Exception.class)
    default E save(E entity){
        return getBaseRepository().save(entity);
    }

    /**
     *添加或更新
     *@author ChenBo
     *@date 2021/9/9
     */
    @Transactional(rollbackFor = Exception.class)
    default E saveOrUpdate(E entity){
        return getBaseRepository().saveAndFlush(entity);
    }

    /**
     *批量添加
     *@author ChenBo
     *@date 2021/9/9
     */
    @Transactional(rollbackFor = Exception.class)
    default int saveBatch(List<E> entityList){
        List<E> es = getBaseRepository().saveAllAndFlush(entityList);
        assert es.size() == entityList.size();
        return es.size();
    }

    @Transactional(rollbackFor = Exception.class)
    default int delete(ID id){
        getBaseRepository().deleteById(id);
        return 1;
    }

}
